/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.iasd.youthshelter.datacore.controller;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import pt.iasd.youthshelter.datamodel.ProgressiveClass;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import org.openide.util.lookup.ServiceProvider;
import pt.iasd.youthshelter.datacore.EntityManagerSemaphore;
import pt.iasd.youthshelter.datacore.controller.exceptions.NonexistentEntityException;
import pt.iasd.youthshelter.datamodel.Club;
import pt.iasd.youthshelter.datamodel.Investiture;
import pt.iasd.youthshelter.datamodel.Honor;
import pt.iasd.youthshelter.datamodel.service.ClubController;

/**
 *
 * @author Rui
 */
@ServiceProvider(service=ClubController.class)
public class ClubJpaController implements Serializable, ClubController {

    private EntityManager aquireEntityManager() throws InterruptedException {
        EntityManagerSemaphore.getInstance().getSemaphore().acquire();
        return EntityManagerSemaphore.getInstance().getEntityManager();
    }
    
    private void releaseEntityManager(EntityManager em) {
        if (em != null && em.isOpen()) {
            em.close();
        }
        EntityManagerSemaphore.getInstance().getSemaphore().release();
    }

    @Override
    public void create(Club club) {
        if (club.getProgressiveClassList() == null) {
            club.setProgressiveClassList(new ArrayList<ProgressiveClass>());
        }
        if (club.getInvestitureList() == null) {
            club.setInvestitureList(new ArrayList<Investiture>());
        }
        if (club.getHonorList() == null) {
            club.setHonorList(new ArrayList<Honor>());
        }
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            List<ProgressiveClass> attachedProgressiveClassList = new ArrayList<ProgressiveClass>();
            for (ProgressiveClass progressiveClassListProgressiveClassToAttach : club.getProgressiveClassList()) {
                progressiveClassListProgressiveClassToAttach = em.getReference(progressiveClassListProgressiveClassToAttach.getClass(), progressiveClassListProgressiveClassToAttach.getId());
                attachedProgressiveClassList.add(progressiveClassListProgressiveClassToAttach);
            }
            club.setProgressiveClassList(attachedProgressiveClassList);
            List<Investiture> attachedInvestitureList = new ArrayList<Investiture>();
            for (Investiture investitureListInvestitureToAttach : club.getInvestitureList()) {
                investitureListInvestitureToAttach = em.getReference(investitureListInvestitureToAttach.getClass(), investitureListInvestitureToAttach.getId());
                attachedInvestitureList.add(investitureListInvestitureToAttach);
            }
            club.setInvestitureList(attachedInvestitureList);
            List<Honor> attachedHonorList = new ArrayList<Honor>();
            for (Honor honorListHonorToAttach : club.getHonorList()) {
                honorListHonorToAttach = em.getReference(honorListHonorToAttach.getClass(), honorListHonorToAttach.getId());
                attachedHonorList.add(honorListHonorToAttach);
            }
            club.setHonorList(attachedHonorList);
            em.persist(club);
            for (ProgressiveClass progressiveClassListProgressiveClass : club.getProgressiveClassList()) {
                progressiveClassListProgressiveClass.getClubList().add(club);
                progressiveClassListProgressiveClass = em.merge(progressiveClassListProgressiveClass);
            }
            for (Investiture investitureListInvestiture : club.getInvestitureList()) {
                investitureListInvestiture.getClubList().add(club);
                investitureListInvestiture = em.merge(investitureListInvestiture);
            }
            for (Honor honorListHonor : club.getHonorList()) {
                honorListHonor.getClubList().add(club);
                honorListHonor = em.merge(honorListHonor);
            }
            em.getTransaction().commit();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public void edit(Club club) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            Club persistentClub = em.find(Club.class, club.getId());
            List<ProgressiveClass> progressiveClassListOld = persistentClub.getProgressiveClassList();
            List<ProgressiveClass> progressiveClassListNew = club.getProgressiveClassList();
            List<Investiture> investitureListOld = persistentClub.getInvestitureList();
            List<Investiture> investitureListNew = club.getInvestitureList();
            List<Honor> honorListOld = persistentClub.getHonorList();
            List<Honor> honorListNew = club.getHonorList();
            List<ProgressiveClass> attachedProgressiveClassListNew = new ArrayList<ProgressiveClass>();
            for (ProgressiveClass progressiveClassListNewProgressiveClassToAttach : progressiveClassListNew) {
                progressiveClassListNewProgressiveClassToAttach = em.getReference(progressiveClassListNewProgressiveClassToAttach.getClass(), progressiveClassListNewProgressiveClassToAttach.getId());
                attachedProgressiveClassListNew.add(progressiveClassListNewProgressiveClassToAttach);
            }
            progressiveClassListNew = attachedProgressiveClassListNew;
            club.setProgressiveClassList(progressiveClassListNew);
            List<Investiture> attachedInvestitureListNew = new ArrayList<Investiture>();
            for (Investiture investitureListNewInvestitureToAttach : investitureListNew) {
                investitureListNewInvestitureToAttach = em.getReference(investitureListNewInvestitureToAttach.getClass(), investitureListNewInvestitureToAttach.getId());
                attachedInvestitureListNew.add(investitureListNewInvestitureToAttach);
            }
            investitureListNew = attachedInvestitureListNew;
            club.setInvestitureList(investitureListNew);
            List<Honor> attachedHonorListNew = new ArrayList<Honor>();
            for (Honor honorListNewHonorToAttach : honorListNew) {
                honorListNewHonorToAttach = em.getReference(honorListNewHonorToAttach.getClass(), honorListNewHonorToAttach.getId());
                attachedHonorListNew.add(honorListNewHonorToAttach);
            }
            honorListNew = attachedHonorListNew;
            club.setHonorList(honorListNew);
            club = em.merge(club);
            for (ProgressiveClass progressiveClassListOldProgressiveClass : progressiveClassListOld) {
                if (!progressiveClassListNew.contains(progressiveClassListOldProgressiveClass)) {
                    progressiveClassListOldProgressiveClass.getClubList().remove(club);
                    progressiveClassListOldProgressiveClass = em.merge(progressiveClassListOldProgressiveClass);
                }
            }
            for (ProgressiveClass progressiveClassListNewProgressiveClass : progressiveClassListNew) {
                if (!progressiveClassListOld.contains(progressiveClassListNewProgressiveClass)) {
                    progressiveClassListNewProgressiveClass.getClubList().add(club);
                    progressiveClassListNewProgressiveClass = em.merge(progressiveClassListNewProgressiveClass);
                }
            }
            for (Investiture investitureListOldInvestiture : investitureListOld) {
                if (!investitureListNew.contains(investitureListOldInvestiture)) {
                    investitureListOldInvestiture.getClubList().remove(club);
                    investitureListOldInvestiture = em.merge(investitureListOldInvestiture);
                }
            }
            for (Investiture investitureListNewInvestiture : investitureListNew) {
                if (!investitureListOld.contains(investitureListNewInvestiture)) {
                    investitureListNewInvestiture.getClubList().add(club);
                    investitureListNewInvestiture = em.merge(investitureListNewInvestiture);
                }
            }
            for (Honor honorListOldHonor : honorListOld) {
                if (!honorListNew.contains(honorListOldHonor)) {
                    honorListOldHonor.getClubList().remove(club);
                    honorListOldHonor = em.merge(honorListOldHonor);
                }
            }
            for (Honor honorListNewHonor : honorListNew) {
                if (!honorListOld.contains(honorListNewHonor)) {
                    honorListNewHonor.getClubList().add(club);
                    honorListNewHonor = em.merge(honorListNewHonor);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = club.getId();
                if (findClub(id) == null) {
                    throw new NonexistentEntityException("The club with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            Club club;
            try {
                club = em.getReference(Club.class, id);
                club.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The club with id " + id + " no longer exists.", enfe);
            }
            List<ProgressiveClass> progressiveClassList = club.getProgressiveClassList();
            for (ProgressiveClass progressiveClassListProgressiveClass : progressiveClassList) {
                progressiveClassListProgressiveClass.getClubList().remove(club);
                progressiveClassListProgressiveClass = em.merge(progressiveClassListProgressiveClass);
            }
            List<Investiture> investitureList = club.getInvestitureList();
            for (Investiture investitureListInvestiture : investitureList) {
                investitureListInvestiture.getClubList().remove(club);
                investitureListInvestiture = em.merge(investitureListInvestiture);
            }
            List<Honor> honorList = club.getHonorList();
            for (Honor honorListHonor : honorList) {
                honorListHonor.getClubList().remove(club);
                honorListHonor = em.merge(honorListHonor);
            }
            em.remove(club);
            em.getTransaction().commit();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public List<Club> findClubEntities() {
        return findClubEntities(true, -1, -1);
    }

    @Override
    public List<Club> findClubEntities(int maxResults, int firstResult) {
        return findClubEntities(false, maxResults, firstResult);
    }

    private List<Club> findClubEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Club.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public Club findClub(Integer id) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            return em.find(Club.class, id);
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public int getClubCount() {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Club> rt = cq.from(Club.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return 0;
    }
    
}
